package cn.bonoon.kernel.menus;

import javax.servlet.ServletContext;

import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.util.PathUtil;

/**
 * 服务器资源的解释器
 * @author jackson
 *
 */
public class ServerResourceResolver {
	
	/** 提供静态资源的服务器 */
	private final String staticResouceServer;
	private final String contextPath;
	
	private final static String LOCAL_RESOURCE = "local:";
	private final static String LOCAL_HOST = "localhost";
	
	public ServerResourceResolver(String staticResouceServer, ServletContext servletContext){
		this.staticResouceServer = staticResouceServer;
		this.contextPath = servletContext.getContextPath();
	}
	
	/** 由这个方法来判断资源使用的是本地资源还是资源服务器的资源 */
	public String resource(String path){
		String tpath = path;
		if(StringHelper.isEmpty(tpath)){
			return "";
		}
		
		if(tpath.startsWith(LOCAL_RESOURCE)){
			return PathUtil.path(contextPath, tpath.substring(LOCAL_RESOURCE.length()));
		}
		
		if(StringHelper.isEmpty(staticResouceServer) || staticResouceServer.equals(LOCAL_HOST)){
			return PathUtil.path(contextPath, tpath);
		}
		return PathUtil.path(staticResouceServer, tpath);
	}
	
	public String resource(String path, String defaultPath){
		return resource(StringHelper.get(path, defaultPath));
	}

	/** 非静态资源的路径 */
	public String path(String... paths) {
		return PathUtil.path(contextPath, paths);
	}
}
